package co.dianjiu.aio.client;


import co.dianjiu.aio.util.InputUtils;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.Scanner;

/**
 * @author DianJiu
 * @website https://dianjiu.co
 * @email dianjiu@dianjiu.cc
 * @date 2021/8/2 17:20
 * @desc TODO
 */
public class AIOClient {
    private AsynchronousSocketChannel asc;

    public AIOClient(AsynchronousSocketChannel asc) {
        this.asc = asc;
    }

    public void connect(){
        asc.connect(new InetSocketAddress("127.0.0.1",10010));
    }
    public void write(){
        try {
            //获取控制台输入流
            Scanner scan = new Scanner(System.in);
            scan.useDelimiter("\n");
            String inputData = InputUtils.getString("请输入要发送的内容：").trim();
            asc.write(ByteBuffer.wrap(inputData.getBytes())).get();
            read();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void read() {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        try {
            //把數據读入缓冲区中
            asc.read(buffer).get();
            //切换缓冲区的读取模式
            buffer.flip();
            //构造一个字节数组接受缓冲区中的数据
            byte[] respBytes = new byte[buffer.remaining()];
            buffer.get(respBytes);
            System.out.println("收到服务端回复消息：\n"+new String(respBytes,"utf-8").trim());
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws Exception {
        AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
        AIOClient aioClient = new AIOClient(client);
        aioClient.connect();
        aioClient.write();
    }
}